package com.which.one;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private EditText inputEditText;
    private Button recordButton;
    private ListView displayListView;
    private ArrayList<String> records = new ArrayList<>();
    private ArrayAdapter<String> listAdapter;
    private Random randomGenerator = new Random();
    private String selectionMode = "single"; // Default mode
    private int numberOfDraws = 1; // Default number of draws
    private boolean includeAllYes = true; // Default to checked
    private boolean includeAllNo = true; // Default to checked

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        inputEditText = findViewById(R.id.inputEditText);
        recordButton = findViewById(R.id.recordButton);
        displayListView = findViewById(R.id.displayListView);

        // 替换原来的ArrayAdapter初始化
        listAdapter = new CustomAdapter(this, records);
        displayListView.setAdapter(listAdapter);

        recordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputText = inputEditText.getText().toString().trim();
                if (!inputText.isEmpty()) {
                    records.add(inputText);
                    listAdapter.notifyDataSetChanged();
                    inputEditText.setText(""); // 清空后会触发TextWatcher自动更新按钮状态
                }else{
                    performRandomSelection();
                }

            }
        });

        inputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                updateButtonState();
            }
        });

// 初始化按钮状态
        updateButtonState();

        recordButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                performRandomSelection();
                return true;
            }
        });

        setupToolbarAndSettingsButton();

        displayListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = records.get(position);
                showRandomDecisionDialog(selectedItem);
            }
        });

        // 在设置适配器后添加
        LayoutAnimationController lac = new LayoutAnimationController(
                AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
        lac.setOrder(LayoutAnimationController.ORDER_NORMAL);
        displayListView.setLayoutAnimation(lac);

    }

    private void updateButtonState() {
        String inputText = inputEditText.getText().toString().trim();
        if (inputText.isEmpty()) {
            recordButton.setText("提交");
            recordButton.setBackgroundResource(R.drawable.btn_green);
        } else {
            recordButton.setText("添加");
            recordButton.setBackgroundResource(R.drawable.btn_blue);
        }

        // 强制重绘代码
        recordButton.postInvalidate();
    }

    @SuppressLint("SetTextI18n")
    private void setupToolbarAndSettingsButton() {
        TextView titleTextView = findViewById(R.id.titleTextView);
        ImageButton settingsButton = findViewById(R.id.settingsButton);
        // Set the title with a 1% chance to change it
        double randomValue = randomGenerator.nextDouble();
        if (randomValue < 0.01) {
            titleTextView.setText("WHAT");
        } else if (randomValue < 0.02) {
            titleTextView.setText("WHO");
        } else if (randomValue < 0.03) {
            titleTextView.setText("WHERE");
        } else if (randomValue < 0.04) {
            titleTextView.setText("WHEN");
        } else if (randomValue < 0.05) {
            titleTextView.setText("WHOSE");
        } else if (randomValue < 0.06) {
            titleTextView.setText("WHY");
        } else if (randomValue < 0.07) {
            titleTextView.setText("HOW");
        } else {
            titleTextView.setText("WHICH");
        }

        settingsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSettingsDialog();
            }
        });
    }

    @SuppressLint("ResourceType")
    private void showSettingsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置");

        final RadioGroup radioGroup = new RadioGroup(this);
        RadioButton singleRadioButton = new RadioButton(this);
        singleRadioButton.setId(1);
        singleRadioButton.setText("单次选择");
        RadioButton multipleRadioButton = new RadioButton(this);
        multipleRadioButton.setId(2);
        multipleRadioButton.setText("n次选择");

        radioGroup.addView(singleRadioButton);
        radioGroup.addView(multipleRadioButton);

        final LinearLayout checkBoxLayout = new LinearLayout(this);
        checkBoxLayout.setOrientation(LinearLayout.HORIZONTAL);
        checkBoxLayout.setPadding(0, 16, 0, 0);

        final CheckBox allYesCheckBox = new CheckBox(this);
        allYesCheckBox.setText("都要");
        allYesCheckBox.setChecked(includeAllYes);

        final CheckBox allNoCheckBox = new CheckBox(this);
        allNoCheckBox.setText("都不要");
        allNoCheckBox.setChecked(includeAllNo);

        checkBoxLayout.addView(allYesCheckBox);
        checkBoxLayout.addView(allNoCheckBox);
        
        Button shakeDiceButton = new Button(this);
        shakeDiceButton.setText("摇色子");
        shakeDiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ShaiziActivity.class);
                startActivity(intent);
            }
        });

        Button LunPanButton = new Button(this);
        LunPanButton.setText("俄罗斯轮盘");
        LunPanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LunPanActivity.class);
                startActivity(intent);
            }
        });

        Button ChatButton = new Button(this);
        ChatButton.setText("问一下DickSuck【联网功能】");
        ChatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DeepseekActivity.class);
                startActivity(intent);
            }
        });



        Button AnswerButton = new Button(this);
        AnswerButton.setText("答案之书【AI功能】");
        AnswerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AnswerBookActivity.class);
                startActivity(intent);
            }
        });

        if (selectionMode.equals("single")) {
            singleRadioButton.setChecked(true);
            checkBoxLayout.setVisibility(View.GONE);
        } else {
            multipleRadioButton.setChecked(true);
            checkBoxLayout.setVisibility(View.VISIBLE);
        }

        final EditText numberOfDrawsEditText = new EditText(this);
        numberOfDrawsEditText.setHint("请输入抽取次数");
        numberOfDrawsEditText.setVisibility(selectionMode.equals("multiple") ? View.VISIBLE : View.GONE);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == 1) {
                    selectionMode = "single";
                    numberOfDrawsEditText.setVisibility(View.GONE);
                    checkBoxLayout.setVisibility(View.GONE);
                } else if (checkedId == 2) {
                    selectionMode = "multiple";
                    numberOfDrawsEditText.setVisibility(View.VISIBLE);
                    checkBoxLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        Button clearRecordsButton = new Button(this);
        clearRecordsButton.setText("清屏");
        clearRecordsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearRecords();
            }
        });

        allYesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                includeAllYes = isChecked;
            }
        });

        allNoCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                includeAllNo = isChecked;
            }
        });

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(radioGroup);
        layout.addView(checkBoxLayout);
        layout.addView(numberOfDrawsEditText);
        layout.addView(shakeDiceButton);
        layout.addView(LunPanButton);
        layout.addView(ChatButton);
        layout.addView(AnswerButton);
        layout.addView(clearRecordsButton);
        builder.setView(layout);

        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
            if (selectionMode.equals("multiple")) {
                try {
                    numberOfDraws = Integer.parseInt(numberOfDrawsEditText.getText().toString());
                    if (numberOfDraws < 2 || numberOfDraws > 100) {
                        return;
                    }
                } catch (NumberFormatException e) {
                    Toast.makeText(MainActivity.this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            Toast.makeText(MainActivity.this, "设置已保存", Toast.LENGTH_SHORT).show();
        });

        builder.setNegativeButton(android.R.string.cancel, null);

        builder.show();

    }

    private void updateDisplayListView() {
        listAdapter.clear();
        listAdapter.addAll(records);
        listAdapter.notifyDataSetChanged();
    }

    private void clearRecords() {
        records.clear();
        updateDisplayListView();
    }



    private void performRandomSelection() {
        if (records.size() < 2) {
            Toast.makeText(MainActivity.this, "需要至少两个记录才能进行随机抽取", Toast.LENGTH_SHORT).show();
            return;
        }

        if (selectionMode.equals("single")) {
            showSingleRandomSelectionDialog();
        } else {
            showMultipleRandomSelectionDialog();
        }
    }

    private void showSingleRandomSelectionDialog() {
        int index = randomGenerator.nextInt(records.size());
        String selectedRecord = records.get(index);

        new AlertDialog.Builder(this)
                .setTitle("随机抽取结果")
                .setMessage(selectedRecord)
                .setPositiveButton(android.R.string.ok, null)
                .show();
    }

    private void showMultipleRandomSelectionDialog() {
        List<String> allOptions = new ArrayList<>(records);
        if (includeAllYes) {
            allOptions.add("我全都要");
        }
        if (includeAllNo) {
            allOptions.add("都不要");
        }

        Map<String, Integer> drawResults = new HashMap<>();

        for (int i = 0; i < numberOfDraws; i++) {
            int index = randomGenerator.nextInt(allOptions.size());
            String selectedRecord = allOptions.get(index);
            drawResults.put(selectedRecord, drawResults.getOrDefault(selectedRecord, 0) + 1);
        }

        StringBuilder messageBuilder = new StringBuilder();

        for (Map.Entry<String, Integer> entry : drawResults.entrySet()) {
            messageBuilder.append(entry.getKey()).append(": ").append(entry.getValue()).append(" 次\n");
        }

        new AlertDialog.Builder(this)
                .setTitle("随机抽取结果")
                .setMessage(messageBuilder.toString())
                .setPositiveButton(android.R.string.ok, null)
                .show();
    }

    private void showRandomDecisionDialog(String item) {
        String decision = randomGenerator.nextBoolean() ? "要" : "不要";
        String message = decision + " " + item;

        new AlertDialog.Builder(this)
                .setTitle("随机决策")
                .setMessage(message)
                .setPositiveButton(android.R.string.ok, null)
                .show();
    }

    private class CustomAdapter extends ArrayAdapter<String> {
        public CustomAdapter(Context context, ArrayList<String> items) {
            super(context, R.layout.list_item, items);
        }

        //列表样式：自定义
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
                holder = new ViewHolder();
                holder.textView = convertView.findViewById(R.id.itemText);
                holder.deleteButton = convertView.findViewById(R.id.deleteButton);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.textView.setText(getItem(position));

            View ConvertView = convertView;
            holder.deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final View finalConvertView = ConvertView; // 捕获当前视图

                    // 先执行动画再删除数据
                    ObjectAnimator anim = ObjectAnimator.ofFloat(finalConvertView, View.ALPHA, 1f, 0f);
                    anim.setDuration(300);
                    // 在删除操作中添加滑动动画
                    anim.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            final int targetPos = position;
                            records.remove(targetPos);
                            notifyDataSetChanged();

                            // 添加滑动补偿动画
                            if (displayListView.getFirstVisiblePosition() <= targetPos &&
                                    targetPos <= displayListView.getLastVisiblePosition()) {
                                View nextView = displayListView.getChildAt(targetPos - displayListView.getFirstVisiblePosition());
                                if (nextView != null) {
                                    nextView.setTranslationY(-nextView.getHeight());
                                    nextView.animate()
                                            .translationY(0)
                                            .setDuration(150)
                                            .start();
                                }
                            }
                        }
                    });
                    anim.start();

                    Toast.makeText(MainActivity.this, "项目已删除", Toast.LENGTH_SHORT).show();
                }
            });

            return convertView;
        }

        private class ViewHolder {
            TextView textView;
            ImageButton deleteButton;
        }

    }
}



